import csv
import json
import re
import requests
import erniebot


class TravelPlanner:
    def __init__(self, erniebot_token, amap_keys_file):
        erniebot.api_type = 'aistudio'
        erniebot.access_token = erniebot_token
        self.amap_keys = self.load_amap_keys(amap_keys_file)
        self.current_key_index = 0

    @staticmethod
    def load_amap_keys(amap_keys_file):
        keys = []
        with open(amap_keys_file, 'r', newline='') as file:
            reader = csv.reader(file)
            header = next(reader, None)  # 获取 CSV 文件的头部（第一行）

            if header and 'key' in header:
                key_index = header.index('key')
                for row in reader:
                    if len(row) > key_index:
                        keys.append(row[key_index])

        return keys

    def switch_amap_key(self):
        self.current_key_index = (self.current_key_index + 1) % len(self.amap_keys)

    @staticmethod
    def generate_travel_suggestions(user_data):
        # 使用ERNIE生成旅行建议
        prompt = str(user_data)

        messages = [{"role": "user", "content": prompt}]
        first_response = erniebot.ChatCompletion.create(
            model="ernie-bot",
            messages=messages,
            system="你是一名智能旅行规划助手，请按照我的旅行要求以json格式给出相应的旅游攻略，要求旅行攻略中的键仅能从day1到dayN，"
                   "一天内的行程的键包括景点推荐、餐饮推荐、酒店推荐、商场推荐。注意，请给出具体的酒店名称、餐厅名称和商场名称，"
                   "酒店地点和餐饮地点请根据景点和商场的位置并结合我的旅行要求进行合理推荐，每天推荐的数量不能少于三个。",
            temperature=0.7
        )
        travel_suggestions = first_response.get_result()
        first_match = re.search(r'{.*}', travel_suggestions, re.DOTALL)

        first_content = first_match.group()
        # 解析 JSON 内容
        travel_guide = json.loads(first_content)
        messages.append(first_response.to_message())
        messages.append({'role': 'user', 'content': "请根据上述推荐列表以json格式给出相应的行程安排，要求行程安排中的键仅能从day1到dayN，"
                                                    "一天内的行程的键仅能为具体的时间段(HH:mm-HH:mm)，一天内时间段的键包括行程地点、详细描述。"})
        second_response = erniebot.ChatCompletion.create(
            model="ernie-bot",
            messages=messages,
            temperature=0.7
        )
        travel_plan = second_response.get_result()
        second_match = re.search(r'{.*}', travel_plan, re.DOTALL)

        if second_match:
            second_content = second_match.group()
            travel_plan = json.loads(second_content)
        return travel_guide, travel_plan

    # 使用高德API获取旅游地点信息
    def get_location_details(self, location_name, destination):
        for key in self.amap_keys:
            url = (f'https://restapi.amap.com/v3/place/text?key={key}'
                   f'&keywords={location_name}&city={destination}'
                   f'&output=json')
            try:
                response = requests.get(url)
                data = json.loads(response.text)
                print(int(data['count']))
                if int(data['count']) > 0:
                    location = data['pois'][0]
                    print(location)
                    return {
                        'latitude': location['location'].split(',')[1],
                        'longitude': location['location'].split(',')[0],
                        'type': location['type'],
                        'address': location['address'],
                        'average_cost': location['biz_ext']['cost'],
                        'rating': location['biz_ext']['rating'],
                        'image_url': location.get('photos', [])
                    }
            except Exception as e:
                print(f"Error fetching location details with key {key}: {e}")
                # 如果请求失败，尝试切换到下一个密钥
                continue

        # 如果所有密钥都尝试失败，返回 None
        return None

    def get_nearby_nursing_homes(self, latitude, longitude, radius=1000):
        for key in self.amap_keys:
            url = (f'https://restapi.amap.com/v3/place/around?key={key}'
                   f'&location={longitude},{latitude}&keywords=医院'
                   f'&radius={radius}&sortrule=distance'
                   f'&output=json')

            try:
                response = requests.get(url)
                data = json.loads(response.text)
                print(data)
                if int(data['count']) > 0:
                    nursing_homes = data['pois']
                    results = []
                    for home in nursing_homes:
                        results.append({
                            'name': home['name'],
                            'latitude': home['location'].split(',')[1],
                            'longitude': home['location'].split(',')[0],
                            'address': home['address'],
                            'distance': home['distance'],
                            'tel': home.get('tel'),
                            'type': home['type']
                        })
                    return results
            except Exception as e:
                print(f"Error fetching nursing home details with key {key}: {e}")
                continue

        return None


if __name__ == "__main__":
    erniebot_token = "81aeb512929d8e6b5121064eaed50ad97c44a98f"
    amap_keys_file = "../amap_key.csv"
    travel_planner = TravelPlanner(erniebot_token, amap_keys_file)

    # Example user data (you can replace this with actual user input)
    user_data = {
        "目的地": "西安",
        "旅游天数": "1天"
    }

    # Generate travel suggestions and plans
    travel_guide, travel_plan = travel_planner.generate_travel_suggestions(user_data)
    for day, day_data in travel_plan.items():
        for time_range, details in day_data.items():
            location_name = details.get('行程地点', '')
            if location_name:
                location_details = travel_planner.get_location_details(location_name, user_data["目的地"])
                if location_details:
                    details.update(location_details)
